import time
from datetime import datetime, timedelta

from flask import render_template, request, jsonify, current_app, session, url_for, g, redirect

from info import user_is_login, constants, db
from info.models import User, News, Category
from info.modules.admin import admin_blue
from info.utils.image_storage import storage
from info.utils.response_code import RET


@admin_blue.route('/login', methods=['GET', 'POST'])
def admin_login():
    """
    管理员登录
    """
    if request.method == 'GET':
        # 去 session 中取指定的值
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        # 如果用户id存在，并且是管理员，那么直接跳转管理后台主页
        if user_id and is_admin:
            return redirect(url_for('admin.admin_index'))
        return render_template('admin/login.html')

    # 获取表单的参数
    username = request.form.get('username')
    password = request.form.get('password')

    if not all([username, password]):
        return render_template('admin/login.html', errmsg="参数错误")

    user = None
    try:
        user = User.query.filter(User.mobile == username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg="数据查询错误")
    if not user:
        return render_template('admin/login.html', errmsg="用户不存在")

    if not user.check_password(password):
        return render_template('admin/login.html', errmsg="密码错误")
    if not user.is_admin:
        return render_template('admin/login.html', errmsg="用户身份不对，不是管理员")

    session['user_id'] = user.id
    session['user_name'] = user.nick_name
    session['user_mobile'] = user.mobile
    session['is_admin'] = True

    return redirect(url_for('admin.admin_index'))


@admin_blue.route('/index')
@user_is_login
def admin_index():
    user = g.user
    print(user.avatar_url)

    data = {
        'user': user.to_dict() if user else None
    }
    return render_template('admin/index.html', data=data)


@admin_blue.route('/admin_user_count')
@user_is_login
def admin_user_count():
    total_user_count = 0
    try:
        total_user_count = User.query.filter(User.is_admin == 0).count()
    except Exception as e:
        current_app.logger.error(e)

    month_add_user_count = 0
    try:
        # 获取当前时间
        now = time.localtime()
        # 当月的第一天，字符串
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        # 将字符串转成时间格式
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        month_add_user_count = User.query.filter(User.is_admin == 0,
                                                 User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    day_add_count = 0
    try:
        # 获取当前时间
        # 当月的第一天，字符串
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        # 将字符串转成时间格式
        day_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        day_add_count = User.query.filter(User.is_admin == 0,
                                          User.create_time >= day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    active_date = []
    active_count = []

    now_day = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')

    for num in range(0, 31):
        begin_time = now_day - timedelta(days=num)
        end_time = now_day - timedelta(days=num - 1)
        active_date.append(begin_time.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == 0,
                                      User.last_login >= begin_time, User.last_login < end_time).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    # print(active_count)
    # print(active_date)
    active_date.reverse()
    active_count.reverse()

    data = {
        'total_user': total_user_count,
        'mon_count': month_add_user_count,
        'day_count': day_add_count,
        'active_date': active_date,
        'active_count': active_count
    }
    return render_template('admin/user_count.html', data=data)


@admin_blue.route('/admin_user_list')
def admin_user_list():
    page = request.args.get("page", 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user_data = []
    current_page = 1
    total_page = 1
    try:

        # 查询用户信息
        paginate = User.query.filter(User.is_admin == 0).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        user_data = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        # return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    user_dict_list = []
    for user_ in user_data:
        user_dict_list.append(user_.to_admin_dict())
    data = {
        "users": user_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/user_list.html", data=data)


@admin_blue.route('/news_review')
def admin_news_review():
    key_word = request.args.get('key_word', '')
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    news_data = []
    current_page = 1
    total_page = 1
    try:
        filter = [News.status != 0]
        if key_word:
            filter.append(News.title.contains(key_word))
    # 查询未通过审核的新闻信息
        paginate = News.query.filter(*filter) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_data = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list = []
    for news_ in news_data:
        news_dict_list.append(news_.to_review_dict())
    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_review.html", data=data)


@admin_blue.route('/admin_news_review_detail',methods=['get','post'])
def admin_news_review_detail():

    if request.method == 'GET':
        news_id = request.args.get('news_id')
        new = None
        try:
            new = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        if not new:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

        data = {
            'news':new.to_dict()
        }
        return  render_template('admin/news_review_detail.html',data=data)


    action = request.json.get('action')
    news_id = request.json.get('news_id')

    if not all([action,news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ['accept','reject']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")
    if action == 'accept':
        news.status = 0
    else:
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        news.status = -1
        news.reason = reason
        
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")
    return jsonify(errno=RET.OK, errmsg="审核完成")

@admin_blue.route('/news_edit')
def admin_news_edit():
    key_word = request.args.get('key_word', '')
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    news_data = []
    current_page = 1
    total_page = 1
    try:
        filter = []
        if key_word:
            filter.append(News.title.contains(key_word))
    # 查询未通过审核的新闻信息
        paginate = News.query.filter(*filter) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_data = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list = []
    for news_ in news_data:
        news_dict_list.append(news_.to_review_dict())
    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_edit.html", data=data)

@admin_blue.route('/new_edit_detail', methods=['GET','POST'])
def new_edit_detail():

    if request.method == 'GET':
        new_id = request.args.get('new_id')
        new = None
        try:
            new = News.query.get(new_id)
        except Exception as e:
            current_app.logger.error(e)
        if not new:
            return render_template('admin/news_edit.html', data={"errmsg": "未查询到此新闻"})
        try:
            category_data = Category.query.all()
        except Exception as e:
            return render_template('admin/news_edit.html', data={"errmsg": "数据库错误 "})
        category_dict = []
        for ca in category_data:
            c_dict = ca.to_dict()
            c_dict['is_selected'] = False
            if ca.id == new.category_id:
                c_dict['is_selected'] = True
            category_dict.append(c_dict)
        category_dict.pop(0)
        data = {
            'news':new.to_dict(),
            'category_data':category_dict
        }
        return render_template('admin/news_edit_detail.html',data=data)

    # 1. 获取要提交的数据
    news_id = request.form.get('news_id')
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    category_id = request.form.get("category_id")

    # 1.1 判断数据是否有值
    if not all([title, source, digest, content, category_id,news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 获取图片
    try:
        act_image = request.files.get('index_image').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件错误")
    # 存储图片
    try:
        image_key = storage(act_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="第三方错误")

    new = None
    try:
        new = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not new:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")
    # 新闻标题
    new.title = title
    # 新闻的内容
    new.content = content
    # 新闻的来源
    new.source = source
    # 新闻摘要
    new.digest = digest
    # 新闻的分类
    new.category_id = category_id
    # 新闻的图片
    new.index_image_url = constants.QINIU_DOMIN_PREFIX + image_key
    #
    new.user_id = g.user.id
    # 新闻的状态，1代表待审核，0 代表审核通过
    new.status = 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库修改失败")
    return jsonify(errno=RET.OK, errmsg="新闻格式修改成功")

@admin_blue.route('/news_type', methods=['GET','POST'])
def news_type_detail():
    if request.method == 'GET':
        try:
            category_data = Category.query.all()
        except Exception as e:
            return render_template('admin/news_type.html', data={"errmsg": "数据库错误 "})
        category_dict = []
        for ca in category_data:
            c_dict = ca.to_dict()
            category_dict.append(c_dict)
        category_dict.pop(0)
        data = {
            'category_data':category_dict
        }
        return render_template('admin/news_type.html',data=data)

    cid = request.json.get('id')
    cname = request.json.get('name')
    if not cname:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if not cid:
        cate = None
        try:
            cate =Category.query.filter(Category.name==cname).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")
        if not cate:
            cate = Category()
            cate.name = cname
            try:
                db.session.add(cate)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
                return jsonify(errno=RET.DBERR, errmsg="数据库插入错误")
            return jsonify(errno=RET.OK, errmsg="分类插入成功")
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg="数据已经存在")
    else:
        cate = None
        try:
            cate =Category.query.get(cid)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")
        if not cate:
            return jsonify(errno=RET.NODATA, errmsg="数据不存在")
        cate.name = cname
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据库修改失败")
        return jsonify(errno=RET.OK, errmsg="分类修改成功")

